package com.yonyou.hxjy.utils;

import com.google.gson.Gson;

import com.yonyou.hxjy.entity.YsQueryDto;
import com.yonyou.hxjy.enums.OpenApiUrlEnum;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author nishch
 * @version 1.0
 * @date 2020/3/11
 * @des 自建应用获取token信息
 */
@Component
public class SelfBuildToken {
	
	public String createToken(YsQueryDto dto) throws Exception {
		String token = null;
		int expire = 5400;
		Map<String, Object> params = new HashMap<String, Object>();
		// 除签名外的其他参数
		params.put("appKey", dto.getAppKey());
		params.put("timestamp", String.valueOf(System.currentTimeMillis()));
		// 计算签名
		String signature = SignHelper.sign(params, dto.getAppSecret());
		params.put("signature", signature);
		String responseString = RequestTool.doGet(dto.getTokenUrl() + OpenApiUrlEnum.ACCESS_TOKEN, params);
		Gson gson = new Gson();
		Map result = gson.fromJson(responseString, Map.class);
		if (ResultCode.SUCCESS.getIndex().equals(result.get(ResultCode.SUCCESS.getName()))) {
			Map<String, Object> tokenInfo = (Map<String, Object>) result.get("data");
			token = (String) tokenInfo.get("access_token");
			String[] expires = String.valueOf(tokenInfo.get("expire")).split("\\.");
			expire = Integer.parseInt(expires[0]);
			RedisUtils.set(dto.getTenantId() + ":YsToken", token, expire);
		} else {
			return "";
			// throw new Exception("获取token失败");
		}
		return token;
	}
	
}
